package com.tros.customer.features;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tros.admin.validation.EncryptValue;
import com.tros.customer.notification.MailNotification;

/**
 * Servlet implementation class ShareInv
 */
@WebServlet("/ShareInv")
public class ShareInv extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShareInv() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		Connection connect =null;			 
		HttpSession ses = request.getSession();
		
		String accType = request.getParameter("accType");
		String accNo = request.getParameter("accno");
		String balance = request.getParameter("balAmt");
		String shrNo = request.getParameter("shrNo");
		String shrOption = request.getParameter("shrOption");
	
		String[] parts = shrOption.split("/");
		String compName = parts[0]; 
		String NoofShrs = parts[1];
		
		System.out.println("accType :"+accType);
		System.out.println("balance :"+balance);

		System.out.println("shrNo :"+shrNo);
		System.out.println("accNo :"+accNo);
		System.out.println("accNo :"+shrOption);
		System.out.println("compName :"+compName);
		System.out.println("NoofShrs :"+NoofShrs);
		
		long tot = Long.parseLong(NoofShrs)*Long.parseLong(shrNo);
		
		try{
			 
			  
	           if(Double.parseDouble(balance) < tot)
	           {
	        	   System.out.println("came here ------->balance less");
	        	   ses.setAttribute("invShrResult", "Share Amount Exceeds Account Balance . Please Change Account or Invest in less shares");
			       response.sendRedirect("invPass.jsp");
			       
	           }else
	           {
	        	   System.out.println("came here ------->balance ok");
	        	   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			       connect =DriverManager.getConnection("jdbc:odbc:bank","root", " ");
		           System.out.println("DB Connection created :"+connect);
		           
	        	   Double bal = Double.parseDouble(balance)- tot;
		           System.out.println("----------> amount ---------->"+bal);
		           
		           
		        	   DetectAcc(connect,accType,accNo,bal,ses);
		        	   
		        	   ses.setAttribute("invShrResult", "Share Investment is Successfully Done");
				       response.sendRedirect("invPass.jsp");
				       
				       try{
							
							 UpdateTrans trans = new UpdateTrans(connect,accNo,accType,"Share Investment",String.valueOf(tot),String.valueOf(ses.getAttribute("currentID")));
							 trans.updateTransValues();
							 
							 						 
						}catch(Exception e)
						{
							e.printStackTrace();
							System.out.println(" -----------> Failed in updation trans --------");
						}
				       
				       try{
							
                              updateShare(connect,String.valueOf(ses.getAttribute("currentID")),compName,tot,shrNo);						 
							 						 
						}catch(Exception e)
						{
							e.printStackTrace();
							System.out.println(" -----------> Failed in updation trans --------");
						}     
				         
						
						try{
							
							String email = "";
							String lname = "";
							
							PreparedStatement state=connect.prepareStatement("SELECT * FROM EXISTUSERS WHERE "+"CUSTOMERID="+ses.getAttribute("currentID"));
							ResultSet result=state.executeQuery();
							
							while(result.next()){
								
							      email=result.getString("EMAIL");
							      lname=result.getString("LASTNAME");
							}
							
							state.close();
							
							MailNotification mail = new MailNotification(email);
						    
						    String text = "Hello "+ lname + 
							    		      "\n\n Share Investment is been performed in your"+
							    		      "\n\n Account : "+accType+
							    		      "\n Number : "+accNo+
							    		      "\n Share Amount : "+tot+
							    		       "\n Company Name : "+compName+
							    		        "\n No of shares : "+shrNo+
							    		      "\n\n Note : Please do not reply to this E-Mail Notification";
							    
							mail.sendMail( "Shares Investment", text);
							connect.close();
							
						}catch(Exception e){
							e.printStackTrace();
							System.out.println(" -----------> Failed in Mail notification --------");
						}
		         
	           }
	           
		}catch(Exception e)
		{
			ses.setAttribute("invShrResult", "Share Investment Failure \n Please Try again");
	        response.sendRedirect("invPass.jsp");
			System.out.println("Failed here --------->"+e.getMessage());
	       	e.printStackTrace();
		}
		
		
	}

	private void updateShare(Connection connect, String valueOf, String compName, long tot,
			String shrNo) {
		// TODO Auto-generated method stub
		

        try{			

		    PreparedStatement state1=connect.prepareStatement("INSERT INTO INVSHARES VALUES(?,?,?,?,?)");
		    
		    state1.setString(1,valueOf);
		    state1.setString(2,compName);
		    state1.setString(3,String.valueOf(tot));
		    state1.setString(4,new java.text.SimpleDateFormat("MM/dd/yyyy h:mm:ss a").format(new Date()));
		    state1.setString(5,shrNo);

		    state1.executeUpdate();	
		    state1.close();
			
		}catch(Exception e){
			System.out.println("update table--------->"+e.getMessage());
		}
	}

	private void DetectAcc(Connection connect, String accType, String accNo,
			Double bal, HttpSession ses) {
		// TODO Auto-generated method stub
		
		try{
			PreparedStatement state;
			
			  if(accType.equals("Savings")){				  
				  state=connect.prepareStatement( "UPDATE SAVACC SET ACC_BALANCE=? WHERE "+"CUSTOMERID="+ses.getAttribute("currentID"));            
			  }else
			  {				  
				   state=connect.prepareStatement( "UPDATE CHCKACC SET ACC_BALANCE=? WHERE "+"CUSTOMERID="+ses.getAttribute("currentID"));	           
			  }
			  
			state.setString(1,String.valueOf(bal));
	   	    state.executeUpdate();
	   	    state.close();
	  		System.out.println("---------> connect value ------"+connect);
			
		}catch(Exception e)
		{
			System.out.println("Failed here update amount --------->");
			e.printStackTrace();
		}
		
	}
		
		
	}

